<?php 
/*********************** 
Makes use of SQLite table
users: 
	CREATE TABLE `user` (   
		`username` TEXT NOT NULL,   
		`password` TEXT NOT NULL,   
		`first` TEXT,   
		`last` TEXT,
		`imei` INTEGER,
		`usergroup` TEXT, ) 
*/ 
session_start();
require_once $_SERVER['DOCUMENT_ROOT'].'../system/config.php';

//if already logged in
if (isset($_SESSION['username'])) {
	header('Location: login_page.php');
}
if (!isset($_REQUEST['username']) || !isset($_REQUEST['username'])) {
	$_SESSION['error_message'] = 'Please enter both a username and the password';
	header('Location: login_page.php');
}

// open database
// fail on database errors 
try { 
	$db = new PDO("sqlite:".$DATABASE);
} catch (PDOException $e) {
	die('Sorry, there is a problem with the database');
}

// formulate query for username         
$sql = 'SELECT * FROM user WHERE username = \'' . mysql_real_escape_string($_REQUEST['username']) . '\'';     
$result = $db->query($sql);          
// fail on sql failure     
if (!$result)  {         
	die('Error: Could not connect to login database.');
}          

// get the first user with username in the table (should only be one)	
$user_row = $result->fetch();     
// if there isn't one     
if (!$user_row) {         
	$_SESSION['error_message'] = 'Invalid username and password combination.';
	header('Location: login_page.php');
}
else if ($user_row['activated'] == '0'){
	$_SESSION['error_message'] = 'This account has not been activated, please check email for activation instructions.';
	header('Location: login_page.php');
} 
else if (isset($_REQUEST['password']) && $_REQUEST['password'] && $_REQUEST['password'] != '') {
	if ($user_row['password'] == md5($_REQUEST['password'])) {
		// logged in         
		$_SESSION['first'] = $user_row['first'];
		$_SESSION['last'] = $user_row['last'];
		$_SESSION['username'] = $user_row['username'];
		$_SESSION['imei'] = $user_row['imei'];
		if(isset($_REQUEST['requested_url'])){
			header('Location: ' . $_REQUEST['requested_url']);
		}
		else{
			header('Location: login_page.php');	
		}
	}     
	else {         
		// not logged in.. incorrect password         
		$_SESSION['error_message'] = 'Invalid username and password combination.';
		if(isset($_REQUEST['requested_url'])){
			header('Location: login_page.php?requested_url='. urlencode($_REQUEST['requested_url']));
		}
		else{
			header('Location: login_page.php');
		}
	} 
}
else {
	$_SESSION['error_message'] = 'Please completely fill out the form.';
	header('Location: login_page.php');
}
?>
